from backend.controller.util import *
from backend.models import Performance, Argument, Research, User


def save(request):
    """
    创建、更新
    :param request:
    :return:
    """
    user_id, paper, patent, award, acceptance = (
        format_param(request, "user_id", "paper", "patent", "award", "acceptance"))

    if not user_id:
        return format_response(WRONG_PARAM)

    # if not (paper and patent and award and acceptance):
    #     return format_param(WRONG_PARAM)

    try:
        user = User.objects.get(id=user_id)
    except:
        return format_response(WRONG_PARAM)

    research = Research.objects.all().filter(user_id=user_id)

    if research:
        research = Research.objects.get(user_id=user_id)
        research.paper = json.dumps(paper)
        research.patent = json.dumps(patent)
        research.award = json.dumps(award)
        research.acceptance = json.dumps(acceptance)
        research.save()
        return format_response(SUCCESS)

    try:
        argument = Research(
            user=user,
            paper=json.dumps(paper),
            patent=json.dumps(patent),
            award=json.dumps(award),
            acceptance=json.dumps(acceptance),
        )
        argument.save()
        return format_response(SUCCESS)
    except:
        return format_response(WRONG_PARAM)


def get_by_user(request):
    """
    根据成员获取绩效信息
    :param request:
    :return:
    """
    user_id = request.GET.get('user_id')
    if not user_id:
        return format_response(WRONG_PARAM)
    try:
        item = Research.objects.get(user=user_id)
        data = {
            "paper": item.paper,
            "patent": item.patent,
            "award": item.award,
            "acceptance": item.acceptance,
            "total": item.get_total_research()
        }
        return format_response(SUCCESS, data)
    except:
        data = {
            "paper": [],
            "patent": [],
            "award": [],
            "acceptance": [],
            "total": 0
        }
        return format_response(SUCCESS, data)
